import random
import time
import json
from paho.mqtt import client as mqtt_client

# tlink/P3WX2rX1r/x3422N21N/event/propertyReport/post  tlink/w3i52s51s/t3ii2mi1m/command/setProperty/exec  tlink/X3WI1EIUE/L3QN2aN1a/command/setProperty/exec
# tlink/${productKey}/${deviceName}/command/setProperty/exec_reply
# 定义要监听的主题列表、回复的主题以及参数
from dao.mysqlhelper import MySQLHelper

topics = [
    {"subscribe": "tlink/53Gk5Ik4I/C3R550540/command/setProperty/exec",
     "response": "tlink/53Gk5Ik4I/C3R550540/command/setProperty/exec_reply"},
    {"subscribe": "tlink/X3WI1EIUE/L3QN2aN1a/command/setProperty/exec",
     "response": "tlink/X3WI1EIUE/L3QN2aN1a/command/setProperty/exec_reply"},
    {"subscribe": "tlink/S3Zz55z45/H3yU5jU4j/command/setProperty/exec",
     "response": "tlink/S3Zz55z45/H3yU5jU4j/command/setProperty/exec_reply"},
    {"subscribe": "tlink/S3Zz55z45/d3125A24A/command/setProperty/exec",
     "response": "tlink/S3Zz55z45/d3125A24A/command/setProperty/exec_reply"}
]

# MQTT 17环境代理信息
# broker = '192.168.141.77'
# port = 1884

# MQTT 116环境代理信息
broker = '116.205.232.249'
port = 10015

# 生成客户端ID
client_id = f'testcjm|signmethod=hmacmd5|{random.randint(0, 1000)}'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print(f"Failed to connect, return code {rc}\n")

    client = mqtt_client.Client(client_id)
    client.username_pw_set("admin&admin", "bc219bd32010b7848139d1b131f71585")
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client, topics: list):
    def on_message(client, userdata, msg):
        print(f"Received topic `{msg.topic}`:`{msg.payload.decode()}`")
        rs = json.loads(msg.payload.decode())
        reqid = rs["reqid"]
        # current_timestamp = time.time()
        # # 根据收到的消息的主题确定回复的目标主题和对应的 payload
        for topic_info in topics:
            if msg.topic == topic_info["subscribe"]:
                payload = {
                    "reqid": reqid,
                    "code": 200
                    # "data": topic_info["payload"]
                }
                # 将 payload 转换为字符串
                payload_str = json.dumps(payload)
                # 发布消息到目标主题
                client.publish(topic_info["response"], payload_str)
                print(f"Published topic `{topic_info['response']}`:{payload} ")

    # 循环订阅每个主题
    for topic_info in topics:
        client.subscribe(topic_info["subscribe"])
    client.on_message = on_message


# 把设备设置在线
def edit_sql():
    mysql = MySQLHelper()
    sql_list = ["update iot_device set device_status='online' where device_name='C3R550540'",
                "update iot_device set device_status='online' where device_name='L3QN2aN1a'",
                "update iot_device set device_status='online' where device_name='H3yU5jU4j'",
                "update iot_device set device_status='online' where device_name='d3125A24A'"]
    for sql in sql_list:
        mysql.dml(sql)


def run():
    edit_sql()   # 把设备设置在线   修改对应的device_name即可
    client = connect_mqtt()
    subscribe(client, topics)  # 设置监听和回复的topic
    client.loop_forever()


if __name__ == '__main__':
    run()
